import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { handleTree } from "@/utils/ruoyi";

const user = {
  state: {
    token: getToken(),
    id: "",
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
    contractTypeList: [],
    // 托管类别
    financeContractTypeList: [],
    // 每个菜单项的列头
    contractTypeUpload: [],
    // 所有需要上传图片的列头
    contractUploadItems: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_FINANCECONTRACTTYPE: (state, typeList) => {
      state.financeContractTypeList = typeList;
    },
    SET_CONTRACTUPLOADITEMS: (state, contractUploadItems) => {
      state.contractUploadItems = contractUploadItems;
    },
    SET_CONTRACTTYPEUPLOAD: (state, contractTypeUpload) => {
      state.contractTypeUpload = contractTypeUpload;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve();
            // 缓存账户信息，切换账户使用
            let userObj = {
              username: username,
              password: password,
            };
            let userInfo = JSON.parse(localStorage.getItem("userInfo"));
            console.log("账户信息：", userInfo);
            if (userInfo == null || userInfo == undefined || userInfo == "") {
              let array = [];
              array.push(userObj);
              localStorage.setItem("userInfo", JSON.stringify(array));
            } else {
              for (let i = 0; i < userInfo.length; i++) {
                const element = userInfo[i];
                if (element.username == username) {
                  userInfo.splice(i, 1);
                  break;
                }
              }
              userInfo.unshift(userObj);
              localStorage.setItem("userInfo", JSON.stringify(userInfo));
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? require("@/assets/images/pusong.png")
                : process.env.VUE_APP_BASE_API + user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            // 续费合同的托管合同类别
            let groupIds = [];
            if (
              res.financeContractTypeList &&
              res.financeContractTypeList.length > 0
            ) {
              res.financeContractTypeList.forEach((item) => {
                groupIds.push(item.id);
              });
              commit("SET_FINANCECONTRACTTYPE", res.financeContractTypeList);
            }
            // 合同服务类型列表
            if (res.contractTypeList && res.contractTypeList.length > 0) {
              // 调用若依官方提供的树形结构方法
              res.contractTypeList.forEach((element) => {
                element.label = element.name;
                element.amount = "";
                element.isYearPay = 0;
                element.disabled = false;
                element.noteOrMemo = "";
                element[`amount${element.id}`] = ``; //amount${element.id}
                element[`noteOrMemo${element.id}`] = ``; //noteOrMemo${element.id}
                if (
                  element.name.includes("其他") &&
                  element.name !== "其他服务"
                ) {
                  element.otherNote = "";
                }
              });
              let treeData = handleTree(res.contractTypeList, "id", "parentId");
              // 特定id下的最底层子节点，需要设置groupId为当前特定值,
              for (let i = 0; i < treeData.length; i++) {
                traverse(treeData[i].children, false, null);
              }
              function traverse(children, flag, groupId) {
                if (flag) {
                  // 匹配上了id
                  children.forEach((child) => {
                    if (child.children) {
                      traverse(child.children, true, groupId);
                    } else {
                      child.groupId = groupId;
                    }
                  });
                } else {
                  children.forEach((child) => {
                    if (groupIds.includes(child.id)) {
                      if (child.children) {
                        traverse(child.children, true, child.id);
                      } else {
                        child.groupId = child.id;
                      }
                    } else {
                      if (child.children) {
                        traverse(child.children, false);
                      }
                    }
                  });
                }
              }
              // 缓存合同类型列表
              localStorage.setItem(
                "contractTypeList",
                JSON.stringify(treeData)
              );
            }
            /**
             * 内勤任务和任务管理的图片上传项解析
             * contractTypeUpload：每个合同类型下的图片上传项
             * contractUploadItems：所有图片上传项
             * 根据每个类型对象的remark字段来判断显示哪些上传项
             */
            if (res.contractUploadItems && res.contractUploadItems.length > 0) {
              commit("SET_CONTRACTUPLOADITEMS", res.contractUploadItems);
              commit("SET_CONTRACTTYPEUPLOAD", res.contractTypeUpload);
            }
            commit("SET_ID", user.userId);
            commit("SET_NAME", user.userName);
            commit("SET_AVATAR", avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
